package com.alpsot.spotcheck.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import cn.pda.scan.CardThread;
import cn.pda.scan.ScanThread;

import com.alpsoft.spotcheck.adapter.BackColorListViewAdapter;
import com.alpsoft.spotcheck.db.DBManager;
import com.alpsoft.spotcheck.db.SQLiteTemplate;
import com.alpsoft.spotcheck.db.SQLiteTemplate.RowMapper;
import com.alpsoft.spotcheck.model.EqResult;
import com.alpsoft.spotcheck.model.Equipment;
import com.alpsoft.spotcheck.status.EquipmentType;
import com.alpsoft.spotcheck.util.DataHelper;
import com.alpsoft.spotcheck.util.GlobalVar;
import com.alpsoft.spotcheck.util.SharedPreferencesUtils;
import com.alpsoft.spotcheck.util.UploadDataManager;
import com.alpsoft.spotcheck.util.Utils;
import com.alpsot.lkspotcheck.R;

/**
 * 小时点检
 * @author Nasir
 *
 */
public class CheckClazz extends Fragment implements OnClickListener {

	private ListView listview;
	private DBManager dbManager;
	private SQLiteDatabase db;
	private SimpleAdapter adapter;
	private List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
	private final int REQUEST = 1;
	private final int RESULT = 2;
	private DataHelper dh;
	private Context context;
	private SQLiteTemplate st;
	private Intent intent;
	private String[] pcode = new String[6];
	private int curs = 0;
	private Button tab_back;
	private Button upload;
	private View view;
	// 震动参数
	private long[] pattern = { 100, 400, 100, 400 }; // 停止 开启 停止 开启

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflateAndSetupView(inflater, container, savedInstanceState,
				R.layout.activity_tab_eq_listview);
		tab_back = (Button) view.findViewById(R.id.tab_back);
		upload = (Button) view.findViewById(R.id.upload);
		tab_back.setOnClickListener(this);
		upload.setOnClickListener(this);

		return view;
	}

	public Handler myHandler = new Handler() {
		@SuppressLint("ShowToast")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GlobalVar.msg_LoginSuccess:
				if (dh.hasLocalData()) {// 有数据上传没数据进行跳转
					UploadDataManager ud = new UploadDataManager(context);
					ud.checkDataUpInfo("update_dj");
				} else {
					msg.obj = "无班点检数据";
					Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
				}
				break;
			case GlobalVar.msg_LoginFailure:
				Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
				break;
			case GlobalVar.msg_UploadSuccess:
				// 跳转至登录页面
				Intent intent = new Intent();
				intent.setClass(context, LoginActivity.class);
				context.startActivity(intent);
				CheckClazz.this.getActivity().finish();
				break;
			case ScanThread.SCAN:
				GlobalVar.scanCode = msg.getData().getString("data").trim();
				Log.i("ddd", GlobalVar.scanCode);
				GlobalVar.scanTime = System.currentTimeMillis();
				getScanEquip();
				break;
			case CardThread.READ:// 按下F1,走的是read
				String data = msg.getData().getString("data");
				if (null != data) {
					GlobalVar.scanCode = data.substring(0, 12);
				}
				GlobalVar.scanTime = System.currentTimeMillis();
				msg.obj = getScanEquip();
				if (msg.obj != null) {
					Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
				}
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dh = new DataHelper(context);
		context = this.getActivity();
		dbManager = DBManager.getInstance(context, GlobalVar.databaseName);
		st = SQLiteTemplate.getInstance(dbManager, false);
		intent = this.getActivity().getIntent();
		curs = 0;
		pcode[curs] = null;
		dataList = getData(null);
	}

	// 实现页面 返回上级 和 上传退出按钮 点击事件
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tab_back:
			curs--;
			if (curs < 0) {
				curs = 0;
			}
			dataList = getData(pcode[curs]);
			adapter.notifyDataSetChanged();
			break;
		case R.id.upload:
			new AlertDialog.Builder(context)
					.setTitle("保存过的上传后不能再修改，请确认要上传吗？")
					.setIcon(android.R.drawable.ic_dialog_info)
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (dh.hasLocalData()) {
										if (LoginActivity.zhLogin) {
											Utils.loginByName(
													context,
													CheckClazz.this,
													SharedPreferencesUtils
															.getLoginInfo(
																	context)
															.getUserName(),
													SharedPreferencesUtils
															.getLoginInfo(
																	context)
															.getPassword(),
													"CheckClazz");
											GlobalVar.ts.speak("开始上传数据");
										} else {
											Utils.login(
													context,
													CheckClazz.this,
													SharedPreferencesUtils
															.getLoginInfo(
																	context)
															.getIcCode(),
													"CheckClazz");
											GlobalVar.ts.speak("开始上传数据");
										}
									} else {
										Intent intent = new Intent();
										intent.setClass(context,
												LoginActivity.class);
										context.startActivity(intent);
										CheckClazz.this.getActivity().finish();
									}
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// 点击“返回”后的操作,这里不设置没有任何操作
								}
							}).show();
			break;
		}
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		// 显示界面
		adapter = new BackColorListViewAdapter(context, dataList,
				R.layout.activity_tab_eq, new String[] { "name", "number" },
				new int[] { R.id.text1, R.id.text2 });
		listview = (ListView) view.findViewById(R.id.listview);
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				HashMap<String, Object> map = (HashMap<String, Object>) listview
						.getItemAtPosition(position);
				String node_type = (String) map.get("node_type");
				String parentCode = (String) map.get("parentCode");
				String self_code = (String) map.get("self_code");
				// if("BJ".equalsIgnoreCase(node_type)){
				if (EquipmentType.Unit.equalsIgnoreCase(node_type)) {// 如果点击到具体设备,进入该设备点检详情
					String cycle_type = (String) map.get("cycle_type");
					String belongEq = (String) map.get("belongEq");
					Intent intent = new Intent();
					intent.putExtra("cycle_type", cycle_type);
					intent.putExtra("belongEq", belongEq);
					intent.putExtra("tab_code", parentCode);
					// 判断code和time
					if (null != GlobalVar.scanCode
							&& "".equals(GlobalVar.scanCode)
							&& isEffective(self_code)) {
						intent.putExtra("isCheckMan", "true");
					} else {
						intent.putExtra("isCheckMan", "false");
					}
					intent.setClass(context, CheckItemActivity.class);
					CheckClazz.this.getActivity().startActivityForResult(intent, REQUEST);
				} else {

					if (curs > 5) {
						curs = 5;
					}
					pcode[curs] = parentCode != null && !parentCode.equals("") ? parentCode
							: null;
					curs++;
					dataList = getData(self_code);
					adapter.notifyDataSetChanged();
				}
			}
		});
	}

	private View inflateAndSetupView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState, int layoutResourceId) {
		View layout = inflater.inflate(layoutResourceId, container, false);
		return layout;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST && resultCode == RESULT) {
			String code = data.getStringExtra("tabCode");
			dataList = getData(code);
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	private List<Map<String, Object>> getData(String parentCode) {
		// 查询设备
		String sql = genSql(parentCode);
		SQLiteTemplate st = SQLiteTemplate.getInstance(dbManager, false);
		List<EqResult> EqResultList = st.queryForList(
				new RowMapper<EqResult>() {
					@Override
					public EqResult mapRow(Cursor cursor, int index) {
						EqResult eq = new EqResult();
						eq.setEquipmentName(cursor.getString(cursor
								.getColumnIndex("EQUIPMENT_NAME")));
						eq.setConNo(cursor.getString(cursor
								.getColumnIndex("conNo")));
						eq.setEquipmentid(cursor.getString(cursor
								.getColumnIndex("equipmentid")));
						eq.setCycle_type(cursor.getString(cursor
								.getColumnIndex("CYCLE_TYPE")));
						eq.setNode_type(cursor.getString(cursor
								.getColumnIndex("EQUIPMENT_TYPE")));
						eq.setSelf_code(cursor.getString(cursor
								.getColumnIndex("SELF_CODE")));
						eq.setFinishNo(cursor.getString(cursor
								.getColumnIndex("finishNo")));
						eq.setParentCode(cursor.getString(cursor
								.getColumnIndex("PARENT_CODE")));
						// eq.setScan_code(cursor.getString(cursor.getColumnIndex("SCAN_CODE")));
						return eq;
					}
				}, sql.toString(), null);
		dataList.clear();

		for (EqResult eq : EqResultList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", eq.getEquipmentName());
			map.put("number", eq.getConNo());
			map.put("belongEq", eq.getEquipmentid());
			map.put("cycle_type", eq.getCycle_type());
			map.put("node_type", eq.getNode_type());
			map.put("self_code", eq.getSelf_code());
			map.put("parentCode", eq.getParentCode());
			String conStr = eq.getConNo();
			String finishStr = eq.getFinishNo();
			int conNo = 0;
			int finishNo = 0;
			if (conStr != null)
				conNo = Integer.parseInt(conStr);
			if (finishStr != null)
				finishNo = Integer.parseInt(finishStr);
			if (finishNo > 0 && finishNo < conNo)
				map.put("color", "yellow");
			else if (finishNo > 0 && finishNo == conNo)
				map.put("color", "green");
			else
				map.put("color", "transparent");
			dataList.add(map);
		}
		return dataList;
	}

	private String genSql(String parentCode) {
		String con = "";
		if (null == parentCode) {
			con = "(SELECT * FROM EQ_EQUIPMENT EQ WHERE EQ.DEPT_ID is not null)";
		} else {
			con = "(SELECT * FROM EQ_EQUIPMENT EQ WHERE EQ.PARENT_CODE = '"
					+ parentCode + "')";
		}

		StringBuilder sb = new StringBuilder();
		sb.append("SELECT * ");
		sb.append(" FROM ");
		sb.append("( ");
		sb.append("	SELECT COUNT(*) conNo, T.EQUIPMENT_ID equipmentid,A.CYCLE_TYPE FROM ");
		sb.append(con + " T,");
		sb.append("(select * from EQ_EQUIPMENT s, eq_check_item c where s.equipment_id = c.equipment_id and c.CYCLE_TYPE='clazz') A ");
		sb.append(" WHERE A.SELF_CODE LIKE T.SELF_CODE || '%' ");
		sb.append("GROUP BY T.EQUIPMENT_ID  ");
		sb.append(") M ");
		sb.append("LEFT JOIN ");

		sb.append("(SELECT COUNT(*) finishNo,AA.EQUIPMENT_ID from " + con
				+ " AA,(select * from EQ_EQUIPMENT ss, eq_check_item cc,");
		sb.append("eq_check_record rr where ss.equipment_id = cc.equipment_id and cc.CHECK_ITEM_ID = rr.CHECK_ITEM_STRATEGY_ID ");
		sb.append("and cc.CYCLE_TYPE = 'clazz' and rr.check_user_id is not null) BB ");
		sb.append("where BB.SELF_CODE LIKE AA.SELF_CODE || '%' group by AA.EQUIPMENT_ID)  VV  ON vv.EQUIPMENT_ID=M.equipmentid ");

		sb.append(",EQ_EQUIPMENT Z ");
		sb.append("WHERE M.equipmentid = Z.EQUIPMENT_ID");
		return sb.toString();
	}

	private boolean isEffective(String self_code) {
		Equipment obj = st.queryForObject(new RowMapper<Equipment>() {
			@Override
			public Equipment mapRow(Cursor cursor, int index) {
				Equipment eq = new Equipment();
				eq.setEquipmentType(cursor.getString(cursor
						.getColumnIndex("EQUIPMENT_TYPE")));
				eq.setParentCode(cursor.getString(cursor
						.getColumnIndex("PARENT_CODE")));
				eq.setEquipmentId(cursor.getString(cursor
						.getColumnIndex("EQUIPMENT_ID")));
				eq.setSelfCode(cursor.getString(cursor
						.getColumnIndex("SELF_CODE")));
				return eq;
			}
		}, "select * from EQ_EQUIPMENT where SCAN_CODE=?",
				new String[] { GlobalVar.scanCode });
		String eqCode = obj.getSelfCode();
		boolean isParent = isParent(self_code, eqCode);
		Long result = GlobalVar.scanTime - System.currentTimeMillis();
		if (isParent && result <= 5 * 60 * 1000) {
			return true;
		}
		return false;
	}

	private boolean isParent(String code, String rootCode) {
		if (code.equals(rootCode)) {
			return true;
		}
		Equipment obj = st.queryForObject(
				new RowMapper<Equipment>() {
					@Override
					public Equipment mapRow(Cursor cursor, int index) {
						Equipment eq = new Equipment();
						eq.setParentCode(cursor.getString(cursor
								.getColumnIndex("PARENT_CODE")));
						eq.setDeptId(cursor.getString(cursor
								.getColumnIndex("DEPT_ID")));
						return eq;
					}
				}, "select * from EQ_EQUIPMENT where SELF_CODE=?",
				new String[] { code });
		String pCode = obj.getParentCode();
		if (obj.getDeptId() == null) {
			if (pCode.equals(rootCode)) {
				return true;
			} else {
				isParent(pCode, rootCode);
			}
		}
		return false;
	}

	public String getScanEquip() {
		String temp = null;
		Equipment eqObj = st.queryForObject(new RowMapper<Equipment>() {
			@Override
			public Equipment mapRow(Cursor cursor, int index) {
				Equipment eq = new Equipment();
				eq.setEquipmentId(cursor.getString(cursor
						.getColumnIndex("EQUIPMENT_ID")));
				eq.setEquipmentType(cursor.getString(cursor
						.getColumnIndex("EQUIPMENT_TYPE")));
				eq.setEquipmentName(cursor.getString(cursor
						.getColumnIndex("EQUIPMENT_NAME")));
				return eq;
			}
		}, "select * from EQ_EQUIPMENT where SCAN_CODE=?",
				new String[] { GlobalVar.scanCode });
		if (eqObj != null) {
			if (EquipmentType.Unit.equalsIgnoreCase(eqObj.getEquipmentType())) {
				Intent intent1 = new Intent();
				String parentCode1 = eqObj.getParentCode();
				String cycle_type1 = "clazz";
				String belongEq1 = eqObj.getEquipmentId();
				intent1.putExtra("cycle_type", cycle_type1);
				intent1.putExtra("belongEq", belongEq1);
				intent1.putExtra("tab_code", parentCode1);
				intent1.putExtra("isCheckMan", "true");
				intent1.setClass(context, CheckItemActivity.class);
				CheckClazz.this.getActivity().startActivityForResult(intent1, REQUEST);
			} else {
				dataList = getData(eqObj.getEquipmentId());
				adapter.notifyDataSetChanged();
				if (null == dataList || dataList.isEmpty()) {
					temp = "无班点检";
					GlobalVar.ts.speak("无班点检");
				} else {
					temp = "设备、" + eqObj.getEquipmentName();
					GlobalVar.ts.speak("设备、" + eqObj.getEquipmentName());
				}
			}
		} else {
			temp = "查无此设备";
			GlobalVar.ts.speak("查无此设备");
		}
		GlobalVar.scanCode = null;
		return temp;
	}
}
